package com.micai.boss.sms.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.micai.boss.base.constant.ErrorCodeEnum;
import com.micai.boss.base.exception.ServiceException;
import com.micai.boss.base.result.BaseResult;
import com.micai.boss.sms.service.SmsTemplateService;
import com.micai.boss.sms.service.dto.Message;
import com.micai.boss.sms.entity.SmsTemplateEntity;
import com.micai.boss.sms.repository.SmsTemplateRepository;
import com.micai.boss.sms.repository.TemplateParser;
import com.micai.boss.sms.service.SmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/24 14:30
 */
@Service(version = "1.0.0", protocol = {"dubbo", "feign"}, timeout = 10000)
public class SmsTemplateServiceImpl implements SmsTemplateService {

    private static final Logger logger = LoggerFactory.getLogger(SmsTemplateServiceImpl.class);

    @Autowired
    private SmsTemplateRepository smsTemplateRepository;

    @Autowired
    private SmsService smsService;

    @Autowired
    private TemplateParser templateParser;

    @Override
    public BaseResult<Boolean> send(String code, String recipients, Map<String, String> params) {
        BaseResult<Boolean> result = new BaseResult<Boolean>(false);
        try {
            SmsTemplateEntity smsTemplateEntity = smsTemplateRepository.findOneByCode(code);
            if (smsTemplateEntity == null) {
                logger.error("找不到模版:" + code);
                result.setCode(ErrorCodeEnum.系统异常.getCode());
                result.setMessage("此业务短信类型已标记为删除:" + code);
                return result;
            }
            String content = templateParser.parse(smsTemplateEntity.getTemplate(), params);
            Message message = new Message(recipients, content);
            message.setProviderName(smsTemplateEntity.getProviderName());
            BaseResult<Boolean> baseResult = smsService.send(message);
            if(baseResult.getCode() == 200 && baseResult.getData() != null){
                result.setData(baseResult.getData());
            }
            return result;
        } catch (ServiceException e) {
            logger.error(e.getMessage());
            result.setCode(e.getCode());
            result.setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ErrorCodeEnum.系统异常.getCode());
            result.setMessage(ErrorCodeEnum.系统异常.getMessage());
        }
        return result;
    }

}
